package com.fmy.mcsecurity.login.hander;

import com.fmy.mcsecurity.commons.tools.RequestTool;
import com.fmy.mcsecurity.config.filter.UsernamePassParamsHolder;
import com.fmy.mcsecurity.integration.TypeIntegration;
import com.fmy.mcsecurity.integration.TypeIntegrationHolder;
import com.fmy.mcsecurity.token.model.SecurityToken;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0
 * @Author MR.fmy
 * @Description 登录失败处理
 * @Date 2019/5/14 0014 10:22
 **/
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {


    private LoginHandler loginHandler;

    public AuthenticationFailureHandlerImpl(LoginHandler loginHandler) {
        this.loginHandler = loginHandler;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException {
        loginHandler.resultPrefix();
        getFail(UsernamePassParamsHolder.getLoginType(),UsernamePassParamsHolder.getUsername());
        RequestTool.responseWriter(response, HttpStatus.OK, loginHandler.resultFail(e));
    }

    /**
     * 获取后置处理
     */
    private void getFail(String type, String username) {
        for (TypeIntegration integration : TypeIntegrationHolder.getAuthenticators()) {
            if (integration.support(type)) {
                integration.fail(type, username);
            }
        }
    }
}
